package com.nega.modules.controller;

import com.nega.commons.constant.ConstantUtil;
import com.nega.commons.model.MemberUser;
import com.nega.commons.model.Message;
import com.nega.commons.util.DateUtils;
import com.nega.commons.util.RSAUtils;
import com.nega.modules.service.MemberUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author: Garcia
 * @CreateDate: 2019/5/18 14:17
 * @Description: 会员用户中心
 */
@Controller
@RequestMapping("mem")
@Slf4j
public class MemberUserCenterController {

    @Resource
    private MemberUserService memberUserService;

    @RequestMapping("index")
    public String index(Model model){
        MemberUser memberUser = (MemberUser) SecurityUtils.getSubject().getPrincipal();
        MemberUser user = memberUserService.getUserById(String.valueOf(memberUser.getId()));
        model.addAttribute("user",user);
        return "view/main";
    }

    @GetMapping("login")
    public String login(){
        MemberUser memberUser = (MemberUser) SecurityUtils.getSubject().getPrincipal();
        if (memberUser!=null){
            return "redirect:index";
        }
        return "view/login";
    }

    @PostMapping("login")
    public String login(Model model, String username ,String password){

        if (StringUtils.isBlank(username)||StringUtils.isBlank(password)){
            model.addAttribute("erro","账号或密码不能为空");
            return "view/login";
        }

        Subject subject = SecurityUtils.getSubject();
        try{
             subject.login(new UsernamePasswordToken(username, password));
             return "redirect:/scan";
        }catch(UnknownAccountException e){
            log.error("账号不存在");
            model.addAttribute("erro","账号或密码错误");
        }catch (IncorrectCredentialsException e){
            log.error("密码错误");
            model.addAttribute("erro","账号或密码错误");
        }catch (DisabledAccountException e){
            log.error("账号未激活");
            model.addAttribute("erro","账号不存在或没有激活");
        }catch (Exception e){
            log.error("系统异常",e);
            model.addAttribute("erro","系统异常");
        }

        return "view/login";
    }

    @GetMapping("register")
    public String register(Model model){
        model.addAttribute("user",new MemberUser());
        return "view/register";
    }

    @PostMapping("register")
    public String register(Model model,MemberUser user){

        model.addAttribute("user",user);

        try {
            memberUserService.insert(user);
        }catch (Exception e){
            log.error("注册异常",e);
            model.addAttribute("erro","注册失败，请稍后再试");
            return "view/register";
        }

        model.addAttribute("registerInfo",true);

        return "view/accountActive";
    }


    @PostMapping("valcheck")
    @ResponseBody
    public Message valcheck(Model model,MemberUser user){

        Message message = Message.success();

        MemberUser memberUser = null;
        if (StringUtils.isNotBlank(user.getEmail())){
            memberUser =  memberUserService.getUserByEmail(user.getEmail());
        }else if (StringUtils.isNotBlank(user.getMobile())){
            memberUser =  memberUserService.getUserByMobile(user.getMobile());
        }else if (StringUtils.isNotBlank(user.getInstituionCode())){
            memberUser =  memberUserService.getUserByInstituion(user.getInstituionCode());
        }

        if (memberUser == null){
            return message;
        }

        return Message.error("已存在");
    }

    @GetMapping("logout")
    public String logout(){
        SecurityUtils.getSubject().logout();
        return "redirect:/scan";
    }

    @GetMapping("active")
    public String activeEmail(Model model,String token){

        if (StringUtils.isBlank(token)){
            model.addAttribute("erro","参数不能为空，邮箱激活链接失效");
            return "view/accountActive";
        }
        try {
            String data = RSAUtils.decryptByPublicKey(token,ConstantUtil.PUBLICE_KEY);
            String[] val = data.split("-");
            String email =  val[0];
            MemberUser memberUser = memberUserService.getUserByAccount(email);
            if (memberUser == null){
                model.addAttribute("erro","激活链接不存在，邮件激活失败");
                return "view/accountActive";
            }
            if (memberUser.getStatus()){
                model.addAttribute("activeInfo",true);
                return "view/accountActive";
            }
            long time =  Long.parseLong(val[1]);
            if (DateUtils.getHourSize(DateUtils.long2Date(time,DateUtils.YYYY_MM_DD_HH_MM_SS),new Date()) >= 24){
                model.addAttribute("erro","激活链接已过期，邮件激活失败，请重新注册账号");
                return "view/accountActive";
            }
            memberUserService.activeUserByEmail(memberUser.getEmail());
            MemberUser memu = memberUserService.getUserByUserCode(memberUser.getInvitationCode());
            if (memu!=null){
                int num = memu.getInvitationNumber()+1;
                memberUserService.updateInvitaNumberByEmail(memu.getEmail(),num);
            }
        } catch (Exception e) {
            log.error("激活失败",e);
            model.addAttribute("erro","激活链接不存在，邮件激活失败");
            return "view/accountActive";
        }

        model.addAttribute("activeInfo",true);
        return "view/accountActive";
    }
}
